<template>
  <div class="container">
    <div class="top">
      <div>
        <span>
          <span>名称：&nbsp;&nbsp;</span>
          <el-input v-model="searchData.name" style="width: 240px" />
        </span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <el-button type="primary" plain @click="search">查询</el-button>
        <el-button type="primary" plain @click="resetSearch">重置</el-button>
      </div>
      <div>
        <el-button type="primary" @click="handleImport">导入</el-button>
        <el-button type="primary" @click="handleExport">导出</el-button>
        <el-button type="primary" @click="add">新增</el-button>
      </div>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%"
      v-loading="loading"
      height="calc(100% - 20px)"
    >
      <el-table-column type="index" label="序号" width="55"> </el-table-column>
      <el-table-column prop="name" label="联防单位名称"> </el-table-column>
      <el-table-column label="位置">
        <template #default="scope"
          >{{ scope.row.lon + "," + scope.row.lat }}
        </template>
      </el-table-column>
      <el-table-column prop="leader" label="负责人"> </el-table-column>
      <el-table-column prop="phone" label="联系方式"> </el-table-column>
      <el-table-column prop="member" label="成员"> </el-table-column>
      <el-table-column prop="kilometreLocation" label="公里标位置">
      </el-table-column>
      <el-table-column prop="peopleNumber" label="人数"> </el-table-column>
      <el-table-column prop="emergencyPeoplePlace" label="抢险队伍人员常驻地">
      </el-table-column>
      <el-table-column prop="date" label="联防协议">
        <template #default="scope">
          <el-button type="primary" plain @click="details(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作">
        <template #default="scope">
          <el-icon title="编辑" @click="edit(scope.row)">
            <Edit />
          </el-icon>
          &nbsp;
          <el-icon title="删除" @click="del(scope.row)">
            <Delete />
          </el-icon>
        </template>
      </el-table-column>
    </el-table>

    <!-- 编辑对话框 -->
    <el-dialog title="联防单位管理" v-model="open" width="600px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="联防单位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入负责人联系方式" />
        </el-form-item>
        <el-form-item label="成员" prop="member">
          <el-input
            type="textarea"
            v-model="form.member"
            placeholder="请输入成员姓名"
          />
        </el-form-item>
        <!-- <div style="display: flex;justify-content: space-around"> -->
        <!-- <div style="width: 100px;">位置：</div> -->
        <el-form-item label="经度位置" prop="lon">
          <el-input-number v-model="form.lon" />
        </el-form-item>
        <el-form-item label="纬度位置" prop="lat">
          <el-input-number v-model="form.lat" />
        </el-form-item>
        <el-form-item label="公里标位置" prop="kilometreLocation">
          <el-input
            v-model="form.kilometreLocation"
            placeholder="请输入公里标位置"
          />
        </el-form-item>
        <el-form-item label="人数" prop="peopleNumber">
          <el-input v-model="form.peopleNumber" placeholder="请输入人数" />
        </el-form-item>
        <el-form-item label="抢险队伍人员常驻地" prop="emergencyPeoplePlace">
          <el-input
            v-model="form.emergencyPeoplePlace"
            placeholder="请输入抢险队伍人员常驻地"
          />
        </el-form-item>
        <!-- </div> -->
      </el-form>

      <el-upload
        ref="uploadRef"
        style="margin-left: 20%"
        v-model:file-list="fileList"
        accept=".pdf"
        :limit="1"
        :http-request="httpRequest"
      >
        <template #trigger>
          <el-button type="primary">上传</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">只能上传pdf格式文件</div>
        </template>
      </el-upload>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看文件 -->
    <el-dialog title="查看" v-model="show" append-to-body width="80vw">
      <embed
        name="showName"
        :src="showUrl"
        style="overflow: auto; width: 100%; height: 70vh"
        hidden="true"
      />
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      :title="upload.title"
      v-model="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox
                v-model="upload.updateSupport"
              />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              type="primary"
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              @click="importTemplate"
              >下载模板</el-link
            >
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getJoint,
  delJoint,
  addJoint,
  editJoint,
  uploadFile,
} from "@/api/work";
const { proxy } = getCurrentInstance();
const open = ref(false);
const searchData = ref({
  name: "",
});

function search() {
  getJoint(searchData.value).then((res) => {
    tableData.value = res.rows;
  });
}

function resetSearch() {
  searchData.value = {
    name: "",
  };
  getList();
}

const tableData = ref([]);
const loading = ref(true);

function getList() {
  loading.value = true;
  getJoint().then((res) => {
    loading.value = false;
    tableData.value = res.rows;
  });
}
getList();

function add() {
  open.value = true;
  form.value = {};
  fileList.value = [];
}
import { getToken } from "@/utils/auth";
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url:
    import.meta.env.VITE_APP_BASE_API +
    "/sjgtw-emergency/jointDefenceUnit/importData",
});
/** 导入按钮操作 */
function handleImport() {
  upload.title = "导入";
  upload.open = true;
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download(
    "sjgtw-emergency/jointDefenceUnit/downloadTemplate",
    {},
    `template_${new Date().getTime()}.xlsx`
  );
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  if (response.code == 200) {
    proxy.$alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
      "导入结果",
      { dangerouslyUseHTMLString: true }
    );
  } else {
    proxy.$alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.data +
        "</div>",
      "导入失败",
      { dangerouslyUseHTMLString: true }
    );
  }
  getList();
};
/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "sjgtw-emergency/jointDefenceUnit/export",
    {
      ...queryParams.value,
    },
    `联防单位管理${new Date().getTime()}.xlsx`
  );
}

function edit(row) {
  fileList.value = [];
  form.value = row;
  if (form.value.protocolName && form.value.protocolUrl) {
    fileList.value = [
      {
        name: form.value.protocolName,
        url: form.value.protocolUrl,
      },
    ];
  }
  open.value = true;
}

const show = ref(false);
const showUrl = ref("");
const showName = ref("");

function details(row) {
  show.value = true;
  showUrl.value = row.protocolUrl;
  showName.value = row.name;
}

const fileList = ref([]);

function httpRequest(date) {
  console.log(date);
  let file = date.file;
  if (/\.pdf/.test(file.name)) {
    const formData = new FormData();
    formData.append("file", file);
    uploadFile(formData).then((res) => {
      if ((res.code = 200)) {
        ElMessage({
          type: "success",
          message: "上传成功",
        });
        form.value.protocolName = res.data.name;
        form.value.protocolUrl = res.data.url;
      }
    });
  } else {
    fileList.value = [];
    return ElMessage({
      type: "error",
      message: "只能上传pdf格式的文件",
    });
  }
}

function del(data) {
  ElMessageBox.confirm("确认删除吗？", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delJoint(data.id).then((res) => {
        ElMessage({
          type: "success",
          message: "已删除",
        });
        getList();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
}

function cancel() {
  open.value = false;
}

function submitForm() {
  console.log(fileList.value);
  if (fileList.value.length == 0) {
    form.value.protocolName = "";
    form.value.protocolUrl = "";
  }
  proxy.$refs["postRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        editJoint(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addJoint(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postCode: undefined,
    postName: undefined,
    phone: undefined,
  },
  rules: {
    leaderPhone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
    assistantPhone: [
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});
const { queryParams, form, rules } = toRefs(data);
</script>

<style lang="scss" scoped>
.container {
  height: 100%;
  width: 100%;
  padding: 20px;
}

.top {
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: space-between;
}

.end {
  justify-content: flex-end;
}

:deep(.el-table .el-table__cell) {
  text-align: center;
}
:deep(.el-table--border::before) {
  width: 0px;
}
:deep(.el-table--border::after) {
  width: 0px;
}
:deep(.el-input-number) {
  width: 100%;
}
</style>
